package com.ysm.smfu.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.ysm.smfu.holder.BaseHolder;

import java.util.List;


/**
 * ====================
 * 版权所有 违法必究
 *
 * @author wangx
 * @project GooglePlay
 * @file DefaultAdapter
 * @create_time 2016/8/23 0023
 * @github https://github.com/wangxujie
 * @blog http://wangxujie.github.io
 * <p/>
 * ======================
 */
public abstract class DefaultAdapter<T> extends BaseAdapter implements AdapterView.OnItemClickListener {

    protected Object object;
    protected List<T> datas;
    private ListView listView;

    public DefaultAdapter(List<T> datas, ListView listView, Object object) {
        this.datas = datas;
        this.listView = listView;
        this.object = object;
        listView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (position >= listView.getHeaderViewsCount()) {
            position -= listView.getHeaderViewsCount();// 头部据的数量
            onInnerItemClick(position);
        }
    }

    /**
     * 条目的点击事件
     *
     * @param position
     */
    protected void onInnerItemClick(int position) {
    }

    // 条目数量
    @Override
    public int getCount() {
        return datas.size();//增加一个加载更多的条目
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseHolder holder = null;
        if (convertView == null) {
            holder = getHolder(); // 1.initView 初始化
            convertView = holder.getContentView();
        } else {
            holder = (BaseHolder) convertView.getTag();
        }
        T t = datas.get(position);
        holder.setData(t); //  2. 记录数据--->refreshView 真正的显示到界面上

        //调用MoreHolder的getContentView 就会显示 加载更多的条目
        return convertView; //3.返回view对象
    }

    /**
     * 获取 viewholder对象
     *
     * @return
     */
    protected abstract BaseHolder<T> getHolder();

    /**
     * 返回数据源
     *
     * @return
     */
    public List<T> getDatas() {
        return datas;
    }

    public void setDatas(List<T> datas) {
        this.datas = datas;
        notifyDataSetChanged();
    }
}


